<template>
  <el-dialog
    v-model="visible"
    :title="$t('contacts.editFriend.title')"
    width="400px"
    :before-close="handleClose"
  >
    <div class="edit-friend-content" v-if="friend">
      <!-- 好友信息展示 -->
      <div class="friend-preview">
        <el-avatar :src="friend.avatarUrl" :size="60">
          {{ friend.realName?.charAt(0) || friend.username.charAt(0) }}
        </el-avatar>
        <div class="friend-details">
          <h3 class="friend-name">
            {{ friend.realName || friend.username }}
            <el-tag v-if="friend.userType === 'VIP'" type="warning" size="small">VIP</el-tag>
            <el-tag v-if="friend.userType === 'ADMIN'" type="danger" size="small">{{ $t('contacts.friend.userTypes.admin') }}</el-tag>
          </h3>
          <p class="friend-username">@{{ friend.username }}</p>
          <p class="friend-since">
            {{ $t('contacts.friend.friendshipTime') }} {{ formatFriendSince(friend.friendSince) }}
          </p>
        </div>
      </div>

      <el-divider />

      <!-- 编辑表单 -->
      <el-form :model="editForm" label-width="80px" @submit.prevent="handleSave">
        <el-form-item :label="$t('contacts.editFriend.friendGroup')">
          <el-select
            v-model="editForm.groupName"
            :placeholder="$t('contacts.editFriend.selectGroupPlaceholder')"
            filterable
            allow-create
            clearable
          >
            <el-option
              v-for="group in contactsStore.friendGroups"
              :key="group"
              :label="group"
              :value="group"
            />
          </el-select>
          <div class="form-help">
            {{ $t('contacts.editFriend.groupHelp') }}
          </div>
        </el-form-item>

        <el-form-item label="好友备注">
          <el-input
            v-model="editForm.remark"
            placeholder="为这位好友添加备注"
            maxlength="100"
            show-word-limit
            clearable
          />
          <div class="form-help">
            备注仅您可见，方便识别好友身份
          </div>
        </el-form-item>
      </el-form>

      <!-- 操作统计 -->
      <div class="friend-stats">
        <el-descriptions title="好友统计" :column="2" size="small">
          <el-descriptions-item label="用户类型">
            <el-tag :type="getUserTypeColor(friend.userType)" size="small">
              {{ getUserTypeText(friend.userType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="当前分组">
            {{ friend.groupName || '默认分组' }}
          </el-descriptions-item>
          <el-descriptions-item label="当前备注">
            {{ friend.remark || '无备注' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="resetForm">重置</el-button>
        <el-button 
          type="primary" 
          @click="handleSave"
          :loading="saving"
        >
          保存修改
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useContactsStore } from '@/stores/contacts'
import { format } from 'date-fns'

// Props & Emits
const props = defineProps<{
  modelValue: boolean
  friend: any
}>()

const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'updated': []
}>()

// 状态管理
const contactsStore = useContactsStore()

// 响应式数据
const saving = ref(false)

const editForm = reactive({
  groupName: '',
  remark: ''
})

// 计算属性
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 监听好友数据变化，更新表单
watch(() => props.friend, (newFriend) => {
  if (newFriend) {
    editForm.groupName = newFriend.groupName || ''
    editForm.remark = newFriend.remark || ''
  }
}, { immediate: true })

// 监听对话框显示状态，重新加载分组
watch(visible, (newVisible) => {
  if (newVisible) {
    contactsStore.getFriendsList()
  }
})

// 方法
const handleSave = async () => {
  if (!props.friend) return

  try {
    saving.value = true

    // 检查是否有修改
    const hasChanges = 
      editForm.groupName !== (props.friend.groupName || '') ||
      editForm.remark !== (props.friend.remark || '')

    if (!hasChanges) {
      ElMessage.info('没有修改内容')
      visible.value = false
      return
    }

    await contactsStore.updateFriend(props.friend.relationshipId, {
      groupName: editForm.groupName || undefined,
      remark: editForm.remark || undefined
    })

    visible.value = false
    emit('updated')

  } catch (error) {
    console.error('更新好友信息失败:', error)
  } finally {
    saving.value = false
  }
}

const resetForm = () => {
  if (props.friend) {
    editForm.groupName = props.friend.groupName || ''
    editForm.remark = props.friend.remark || ''
    ElMessage.success('已重置为原始值')
  }
}

const handleClose = () => {
  visible.value = false
}



const formatFriendSince = (friendSince: string) => {
  if (!friendSince) return '未知'
  
  try {
    const date = new Date(friendSince)
    return format(date, 'yyyy年MM月dd日', { locale: zhCN })
  } catch {
    return '未知'
  }
}

const getUserTypeColor = (userType: string) => {
  switch (userType) {
    case 'VIP': return 'warning'
    case 'ADMIN': return 'danger'
    default: return 'info'
  }
}

const getUserTypeText = (userType: string) => {
  switch (userType) {
    case 'VIP': return 'VIP用户'
    case 'ADMIN': return '管理员'
    case 'BASIC': return '普通用户'
    default: return '未知'
  }
}
</script>

<style scoped>
.edit-friend-content {
  padding: 8px 0;
}

.friend-preview {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
}

.friend-details {
  flex: 1;
}

.friend-name {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 8px 0;
  font-size: 18px;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.friend-username {
  margin: 0 0 8px 0;
  font-size: 14px;
  color: var(--el-color-primary);
}

.friend-status {
  display: flex;
  align-items: center;
  gap: 6px;
  margin: 0 0 8px 0;
  font-size: 14px;
}



.friend-since {
  margin: 0;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
}

.form-help {
  margin-top: 4px;
  font-size: 12px;
  color: var(--el-text-color-placeholder);
  line-height: 1.4;
}

.friend-stats {
  margin-top: 20px;
  padding: 16px;
  background: var(--el-fill-color-extra-light);
  border-radius: 8px;
}

.text-success {
  color: var(--el-color-success);
}

.text-info {
  color: var(--el-color-info);
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

:deep(.el-descriptions__title) {
  font-size: 14px;
  font-weight: 500;
  margin-bottom: 12px;
}

:deep(.el-descriptions__label) {
  font-size: 12px;
}

:deep(.el-descriptions__content) {
  font-size: 12px;
}

:deep(.el-divider) {
  margin: 20px 0;
}
</style>
